package com.store.controller;

import com.store.common.Result;
import com.store.dto.CartAddRequest;
import com.store.dto.CartUpdateRequest;
import com.store.service.CartService;
import com.store.vo.CartVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 购物车控制器
 */
@Slf4j
@RestController
@RequestMapping("/cart")
@RequiredArgsConstructor
public class CartController {
    
    private final CartService cartService;
    
    /**
     * 获取购物车列表
     */
    @GetMapping("/list")
    public Result<List<CartVO>> getCartList(HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            List<CartVO> cartList = cartService.getCartList(userId);
            return Result.success(cartList);
        } catch (Exception e) {
            log.error("获取购物车列表失败", e);
            return Result.error("获取购物车列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 添加商品到购物车
     */
    @PostMapping
    public Result<String> addToCart(@Validated @RequestBody CartAddRequest cartRequest,
                                     HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            cartService.addToCart(userId, cartRequest);
            return Result.success("添加成功");
        } catch (Exception e) {
            log.error("添加购物车失败", e);
            return Result.error("添加购物车失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新购物车商品数量
     */
    @PutMapping
    public Result<String> updateCart(@Validated @RequestBody CartUpdateRequest cartRequest,
                                      HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            cartService.updateCart(userId, cartRequest);
            return Result.success("更新成功");
        } catch (Exception e) {
            log.error("更新购物车失败", e);
            return Result.error("更新购物车失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除购物车记录
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteCart(@PathVariable Long id, HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            cartService.deleteCart(userId, id);
            return Result.success("删除成功");
        } catch (Exception e) {
            log.error("删除购物车失败", e);
            return Result.error("删除购物车失败：" + e.getMessage());
        }
    }
    
    /**
     * 清空购物车
     */
    @DeleteMapping("/clear")
    public Result<String> clearCart(HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            cartService.clearCart(userId);
            return Result.success("清空成功");
        } catch (Exception e) {
            log.error("清空购物车失败", e);
            return Result.error("清空购物车失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取购物车商品数量
     */
    @GetMapping("/count")
    public Result<Long> getCartCount(HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            Long count = cartService.getCartCount(userId);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取购物车数量失败", e);
            return Result.error("获取购物车数量失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除购物车记录
     */
    @DeleteMapping("/batch")
    public Result<String> batchDelete(@RequestBody List<Long> cartIds, HttpServletRequest request) {
        try {
            Long userId = getUserId(request);
            cartService.batchDelete(userId, cartIds);
            return Result.success("删除成功");
        } catch (Exception e) {
            log.error("批量删除购物车失败", e);
            return Result.error("批量删除购物车失败：" + e.getMessage());
        }
    }
    
    /**
     * 从请求中获取用户ID
     */
    private Long getUserId(HttpServletRequest request) {
        Object userIdObj = request.getAttribute("userId");
        if (userIdObj == null) {
            throw new RuntimeException("未登录或登录已过期");
        }
        return Long.valueOf(userIdObj.toString());
    }
}

